﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using com.huawei.esdk.tp.oa.DataType;
using System.Numerics;
using System.Security.Cryptography;
using com.huawei.esdk.tp.oa.local;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Net;

namespace com.huawei.esdk.tp.oa.Utils
{
    public class RSA2048
    {
        PlatformKeyServiceProvider platformKey;

        private const int maxLength = 256;

        public RSA2048(string platformKeyURL)
        {
            platformKey = PlatformKeyServiceProvider.Instance(platformKeyURL);
        }

        public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受     
            return true;
        }  

        /// <summary>        
        /// RSA加密       
        /// </summary>        
        /// <param name="publickey"></param>        
        /// <returns></returns>        
        public string RSAEncrypt(string password)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);

            TPOASDKResponse<string> result = new TPOASDKResponse<string>();
            result = platformKey.getPublicKey();

            byte[] keyByte = Convert.FromBase64String(result.result);

            byte[] modulus = new byte[256];
            for (int i = 33; i < 289; i++)
            {
                modulus[i - 33] = keyByte[i];
            }

            byte[] exponent = new byte[3];
            for (int i = 291; i < keyByte.Length; i++)
            {
                exponent[i - 291] = keyByte[i];
            }

            //把3个变量转化为System.Numerics.BigInteger 
            var modulusBigInteger = new BigInteger(modulus);

            var exponentBigInteger = new BigInteger(exponent);

            var modulusBytes = modulusBigInteger.ToByteArray();

            var exponentBytes = exponentBigInteger.ToByteArray();

            var rsaCsp = new RSACryptoServiceProvider();
            RSAParameters parameters = new RSAParameters();
            parameters.Modulus = modulusBytes;
            parameters.Exponent = exponentBytes;
            rsaCsp.ImportParameters(parameters);

            var cipherbytes = rsaCsp.Encrypt(Encoding.UTF8.GetBytes(password), false);

            string cipher = Convert.ToBase64String(cipherbytes);
            return cipher;

        }
    }
}
